<?php
namespace app\admin\controller\main;

use app\common\controller\AdminController;
use app\common\model\Article as Model;
use app\common\model\ArticleAttribute;
use app\common\model\ArticleCategory;
use app\common\model\Tag;
use think\App;

/**
 * @ControllerAnnotation(title="文章管理")
 * Class Article
 * @package app\admin\controller\main
 */
class Article extends AdminController
{

    use \app\admin\traits\Curd;
    /**
     * 初始化方法
     */
    public function __construct(App $app)
    {
        parent::__construct($app);
        parent::initialize();
        $this->model=new Model();
        $cateTree=(new ArticleCategory())->tree();

        $this->assign('category_level_list', $cateTree);
    }


    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            [$page, $limit, $where] = $this->buildTableParames();

            $count = $this->model->count('status');
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->field('id,sort,title,check_status,view,category_id,status,create_time')
                ->select();

            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }

        $pidCateList=ArticleCategory::getPidCateList();

        $this->assign('pidCateListJson', json_encode(['data'=>$pidCateList]));
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            try {
                if ($post['publish_time'] > date('Y-m-d H:i:s')) {
                    $post['status'] = 0; //定时发布
                } else{
                    $post['publish_time']=date('Y-m-d H:i:s');
                    $post['status'] = 1;
                }
                if($post['content']&&(!$post['keywords']||!$post['cover_img']||!$post['description'])){
                    $CDK=Model::getCDK($post['content'],$post['title']);
                    if(!$post['keywords']&&$CDK['K']){
                        $post['keywords']=$CDK['K'];
                    }
                    if(!$post['cover_img']&&$CDK['C']){
                        $post['cover_img']=$CDK['C'];
                    }
                    if(!$post['description']&&$CDK['D']){
                        $post['description']=$CDK['D'];
                    }
                }
                if($post['title']&&!$post['seo_title']){
                    $post['seo_title']=$post['title'];
                }
                $save=$this->model->createNew($post);
            } catch (\Exception $e) {
                $this->error('保存失败'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }

        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id='')
    {
        if(!$id){
            $id=request()->param()['id'];
        }
        $attributeModel=new ArticleAttribute();
        $row = $this->model->find($id);
        $attribute=$attributeModel->where('article_id',$id)->find();
        $item=$row->toArray()+($attribute?$attribute->toArray():[]);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            if(isset($post['check_status'])&&$post['check_status']==1){
                $post['status']=1;
            }elseif($post['publish_time'] > date('Y-m-d H:i:s')) {
                $post['status'] = 0; //定时发布
            }
            if(!$post['publish_time']){
                $post['publish_time']=date('Y-m-d H:i:s');
            }
            if($post['content']&&(!$post['keywords']||!$post['cover_img']||!$post['description'])){
                $CDK=Model::getCDK($post['content'],$post['title']);
                if(!$post['keywords']&&$CDK['K']){
                    $post['keywords']=$CDK['K'];
                }
                if(!$post['cover_img']&&$CDK['C']){
                    $post['cover_img']=$CDK['C'];
                }
                if(!$post['description']&&$CDK['D']){
                    $post['description']=$CDK['D'];
                }
            }
            if($post['title']&&!$post['seo_title']){
                $post['seo_title']=$post['title'];
            }
            if(isset($post['reward_amount'])&&$post['reward_amount']){
                $post['reward_status']=1;
            }
            $this->model->filterFields($post,$mainData, $attributeData,$otherData);
            try {
                $save = $row->save($mainData);
                if(!$attribute) {
                    $attribute = $attributeModel;
                    $attributeData['article_id']=$id;
                }
                $attribute->save($attributeData);
                if (isset($otherData['attachlink'])) {
                    $attach=$otherData['attachlink'];
                    $attach['subject_id']=$id;
                    $attach['subject']='ARTICLE';
                    hooks('attachlink.link_save', $attach);
                }
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $refuse_tpl=sysconfig('article.refuse_tpl');
        if($refuse_tpl){
            $refuse_tpl=json_encode(explode("\n",$refuse_tpl));
        }

        $this->assign('refuseTpl', $refuse_tpl);
        $this->assign('row', $item);
        return $this->fetch();
    }

    public function changeCategory(){
        $data=$this->request->param();
        $ids=$data['id'];
        $this->model->whereIn('id',$ids)->save(['category_id'=>$data['category_id']]);
        return json(['code'=>1,'msg'=>'修改成功']);
    }

}